package org.example.friend_test.service.impl;

import org.example.friend_test.entity.Friend;
import org.example.friend_test.mapper.FriendMapper;
import org.example.friend_test.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 朋友服务实现类
 */
@Service
public class FriendServiceImpl implements FriendService {
    
    @Autowired
    private FriendMapper friendMapper;
    
    @Override
    public List<Friend> findAllFriendsByUserId(Long userId) {
        return friendMapper.selectByUserId(userId);
    }
    
    @Override
    public List<Friend> findAllFriends() {
        // 兼容旧版本，返回空列表（需要指定用户ID）
        return Collections.emptyList();
    }
    
    @Override
    public Friend findFriendById(Long id, Long userId) {
        Friend friend = friendMapper.selectById(id);
        // 验证权限：只能查看自己的朋友
        if (friend != null && friend.getUserId().equals(userId)) {
            return friend;
        }
        return null;
    }
    
    @Override
    public List<Friend> findFriendsByName(String name, Long userId) {
        return friendMapper.selectByNameAndUserId(name, userId);
    }
    
    @Override
    public List<Friend> findFriendsByRelationship(String relationship, Long userId) {
        return friendMapper.selectByRelationshipAndUserId(relationship, userId);
    }
    
    @Override
    public Friend createFriend(Friend friend, Long userId) {
        // 设置用户ID
        friend.setUserId(userId);
        friendMapper.insert(friend);
        return friend;
    }
    
    @Override
    public Friend updateFriend(Friend friend, Long userId) {
        // 验证权限：只能更新自己的朋友
        Friend existingFriend = friendMapper.selectById(friend.getId());
        if (existingFriend != null && existingFriend.getUserId().equals(userId)) {
            // 确保用户ID不被修改
            friend.setUserId(userId);
            friendMapper.update(friend);
            return friend;
        }
        return null;
    }
    
    @Override
    public boolean deleteFriend(Long id, Long userId) {
        // 验证权限：只能删除自己的朋友
        Friend friend = friendMapper.selectById(id);
        if (friend != null && friend.getUserId().equals(userId)) {
            return friendMapper.deleteById(id) > 0;
        }
        return false;
    }
}
